#include <iostream>
#include <string>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const int NUM = 5;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void * threatRun(void * args)
{
    string name=static_cast<const char *>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        cout<<name<<" 线程正运行"<<endl; 
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    pthread_t tid[NUM];
    for(int i=0;i<NUM;i++)
    {
        char * buf=new char[64];
        snprintf(buf,64,"thread-%d",i+1);
        pthread_create(tid+i,nullptr,threatRun,buf);
    }
    sleep(3); //让所有线程都处于等待状态
    while(true)
    {
        cout<<"main wakeup the thread"<<endl;
        //pthread_cond_signal(&cond); //逐个唤醒线程
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    for(int i=0;i<NUM;i++)
    {
        pthread_join(tid[i],nullptr);
    }

    return 0;
}